package com.codecash.interceptors;

import com.codecash.util.JwtUtil;
import com.codecash.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            sendErrorResponse(response, "未授权访问，请登录");
            return false;
        }

        try {
            // 解析 token 并获取用户 ID 和其他信息
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Long userId = ((Number) claims.get("id")).longValue(); // 确保 userId 是 Long 类型

            // 检查 Redis 中是否有此用户的 token，并与请求的 token 进行匹配
            String redisTokenKey = "user_token:" + userId;
            String redisToken = stringRedisTemplate.opsForValue().get(redisTokenKey);

            if (redisToken == null || !redisToken.equals(token)) {
                sendErrorResponse(response, "token 已失效，请重新登录");
                return false;
            }

            // 将用户信息存储到 ThreadLocal 中，以便后续接口使用
            ThreadLocalUtil.set(claims);
            return true; // token 有效，允许访问
        } catch (Exception e) {
            sendErrorResponse(response, "无效的 token，请重新登录");
            return false;
        }
    }

    // 辅助方法：用于发送未授权的响应信息
    private void sendErrorResponse(HttpServletResponse response, String message) throws Exception {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\": 401, \"message\": \"" + message + "\"}");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理 ThreadLocal 中的数据，防止内存泄漏
        ThreadLocalUtil.remove();
    }
}
